package com.atguigu.gulimall.authserver.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.HttpUtils;
import com.atguigu.common.utils.R;
import com.atguigu.common.vo.MemberResponseVo;
import com.atguigu.common.vo.SocialUserVo;
import com.atguigu.gulimall.authserver.feign.MemberFeignService;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpResponse;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpSession;
import java.util.HashMap;

import static com.atguigu.common.constant.AuthServerConstant.LOGIN_USER;

/**
 * @author jingchun
 * @create 2024-07-17 16:05
 */
@Controller
@Slf4j
public class Oauth2Controller {

	@Autowired
	MemberFeignService memberFeignService;

	@GetMapping(value = "/oauth2.0/gitee/success")
	public String gitee(@RequestParam String code, HttpSession session) throws Exception {
		HashMap<String, String> map = new HashMap<>();
		map.put("grant_type", "authorization_code");
		map.put("code", code);
		map.put("client_id", "8ed2a86d51bd0ed1331e18449467866badf81d415fab3e56dd7b237380fe5b3c");
		map.put("redirect_uri", "http://auth.gulimall.com/oauth2.0/gitee/success");
		map.put("client_secret", "398159c96a3c350bde449dd048d8e8ccd7c822acb1eebfe090abbfe10bdf0454");

		//1. 根据用户授权 用code返回token
		HttpResponse response = HttpUtils.doPost("https://gitee.com", "/oauth/token", "post", new HashMap<>(), map,
				new HashMap<>());

		//2.处理
		if (response.getStatusLine().getStatusCode() == 200) {
			//	获取token成功//access_token
			response.getEntity();
			String json = EntityUtils.toString(response.getEntity());
			GiteeTokens giteeTokens = JSON.parseObject(json, GiteeTokens.class);
			//System.out.println("giteeToken的内容" + giteeTokens);
			String accessToken = giteeTokens.getAccess_token();


			//查询gitee用户信息
			HashMap<String, String> token = new HashMap<>();
			token.put("access_token", accessToken);
			HttpResponse response1 = HttpUtils.doGet("http://gitee.com", "/api/v5/user", "get", new HashMap<>(),
					token);

			//转换成为用户信息对象
			String json1 = EntityUtils.toString(response1.getEntity());
			SocialUserVo giteeUser = JSON.parseObject(json1, SocialUserVo.class);
			giteeUser.setAccess_token(giteeTokens.getAccess_token());
			giteeUser.setExpires_in(giteeTokens.getExpires_in());
			//System.out.println("giteeUser的内容" + giteeUser);

			//1）、当前用户如果是第一次进网站，自动注册进来（为当前社交用户生成一个会员信息，以后这个社交账号就对应指定的会员）
			//登录或者注册这个社交用户
			//调用远程服务
			R oauthLogin = memberFeignService.oauthLogin(giteeUser);
			if (oauthLogin.getCode() == 0) {
				MemberResponseVo data = oauthLogin.getData("data", new TypeReference<MemberResponseVo>() {
				});
				//log.info("登录成功：用户信息：{}", data.toString());

				//1、第一次使用session，命令浏览器保存卡号，JSESSIONID这个cookie
				//以后浏览器访问哪个网站就会带上这个网站的cookie
				//TODO 1、默认发的令牌。当前域（解决子域session共享问题）
				//TODO 2、使用JSON的序列化方式来序列化对象到Redis中
				session.setAttribute(LOGIN_USER,data);

				//2、登录成功跳回首页
				return "redirect:http://gulimall.com";
			} else {

				return "redirect:http://auth.gulimall.com/login.html";

			}
		}else {

			return "redirect:http://auth.gulimall.com/login.html";

		}


	}
}
